import { computed, onMounted } from "vue";
import { useListPage } from "@/composables/useListPage";
import orderApi, {
  type OrderListParams,
  type OrderListResult,
  type OrderRecord
} from "@/api/system/order/orders";

interface OrderFilterForm {
  keyword: string;
  status: string | number;
  pay_status: string | number;
  ship_status: string | number;
  refund_status: string | number;
}

const DEFAULT_FILTER: OrderFilterForm = {
  keyword: "",
  status: "",
  pay_status: "",
  ship_status: "",
  refund_status: ""
};

const ORDER_STATUS_OPTIONS = [
  { label: "全部状态", value: "" },
  { label: "待确认", value: 0 },
  { label: "待支付", value: 1 },
  { label: "待客服指派", value: 2 },
  { label: "待物流安排", value: 3 },
  { label: "待卖家发货", value: 4 },
  { label: "运输中", value: 5 },
  { label: "已完成", value: 6 },
  { label: "已取消", value: 7 },
  { label: "售后处理中", value: 8 }
];

const PAY_STATUS_OPTIONS = [
  { label: "全部", value: "" },
  { label: "待支付", value: 0 },
  { label: "已支付", value: 1 },
  { label: "已退款", value: 2 }
];

const SHIP_STATUS_OPTIONS = [
  { label: "全部", value: "" },
  { label: "待发货", value: 0 },
  { label: "已发货", value: 1 },
  { label: "部分发货", value: 2 },
  { label: "已签收", value: 3 }
];

const REFUND_STATUS_OPTIONS = [
  { label: "全部", value: "" },
  { label: "无售后", value: 0 },
  { label: "处理中", value: 1 },
  { label: "已完成", value: 2 }
];

const formatCurrency = (value: number | null | undefined) => {
  if (value === null || value === undefined) return "-";
  if (!Number.isFinite(value)) return String(value);
  return Number(value).toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

const formatStatusTag = (status: number) => {
  switch (status) {
    case 5:
    case 6:
      return "success";
    case 7:
      return "danger";
    case 8:
      return "warning";
    case 3:
    case 4:
      return "info";
    default:
      return "primary";
  }
};

export function useOrderList() {
  const {
    formState: filterForm,
    pagination,
    dataList,
    loading,
    onSearch,
    resetForm,
    handlePageChange,
    handleSizeChange
  } = useListPage<OrderFilterForm, OrderRecord, OrderListResult>(
    {
      fetch: params => orderApi.fetchList(params as unknown as OrderListParams)
    },
    DEFAULT_FILTER,
    {},
    {
      paramsAdapter: params => {
        const query: OrderListParams = {
          page: params.page,
          page_size: params.page_size
        };

        const keyword = params.keyword?.trim();
        if (keyword) query.keyword = keyword;

        if (params.status !== "" && params.status !== undefined) {
          query.status = Number(params.status);
        }
        if (params.pay_status !== "" && params.pay_status !== undefined) {
          query.pay_status = Number(params.pay_status);
        }
        if (params.ship_status !== "" && params.ship_status !== undefined) {
          query.ship_status = Number(params.ship_status);
        }
        if (params.refund_status !== "" && params.refund_status !== undefined) {
          query.refund_status = Number(params.refund_status);
        }

        return query;
      },
      responseAdapter: (response: OrderListResult) => {
        const paginationMeta = response?.pagination ?? {
          total: 0,
          pageSize: 10,
          currentPage: 1
        };

        return {
          list: response?.list ?? [],
          total: Number(paginationMeta.total ?? 0),
          pageSize: Number(paginationMeta.pageSize ?? 10),
          currentPage: Number(
            paginationMeta.currentPage ?? paginationMeta.page ?? 1
          )
        };
      }
    }
  );
  const tableData = computed(() => dataList.value ?? []);

  const columns: TableColumnList = [
    { label: "订单号", prop: "order_no", width: 180 },
    {
      label: "买家信息",
      prop: "buyer",
      minWidth: 200,
      align: "left",
      slot: "buyer"
    },
    {
      label: "卖家信息",
      prop: "seller",
      minWidth: 200,
      align: "left",
      slot: "seller"
    },
    {
      label: "金额概览",
      prop: "amount",
      minWidth: 200,
      align: "left",
      slot: "amount"
    },
    {
      label: "状态",
      prop: "status",
      width: 160,
      align: "left",
      slot: "status"
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 220,
      align: "left",
      slot: "remark"
    },
    { label: "创建时间", prop: "create_time", width: 180 }
  ];

  const handleSearch = () => {
    filterForm.page = 1;
    onSearch();
  };

  const handleResetFilters = () => {
    resetForm();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    filterForm,
    pagination,
    tableData,
    columns,
    loading,
    orderStatusOptions: ORDER_STATUS_OPTIONS,
    payStatusOptions: PAY_STATUS_OPTIONS,
    shipStatusOptions: SHIP_STATUS_OPTIONS,
    refundStatusOptions: REFUND_STATUS_OPTIONS,
    handleSearch,
    handleResetFilters,
    handlePageChange,
    handleSizeChange,
    formatCurrency,
    formatStatusTag
  };
}
